package com.example.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/login")
public class login_session extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(login_session.class);
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        PrintWriter out = resp.getWriter();

        // 模拟登录逻辑
        if ("admin".equals(username) && "123456".equals(password)) {
            HttpSession session = req.getSession();
            logger.info("session对象创建");
            session.setAttribute("user", username);
            logger.info("session对象将用户名传递到域中");
            System.out.println("session获取到的用户名"+session.getAttribute("user"));
            out.write("{\"success\": true, \"message\": \"登录成功\"}");
        } else {
            // 登录失败
            out.write("{\"success\": false, \"message\": \"用户名或密码错误\"}");
        }

        out.flush();
        out.close();
    }
}
